﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
using Microsoft.Win32;
using System.Diagnostics;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;



namespace 玄鸟刀剑2
{



    public partial class Form4 : Form


    {
       

        /// <summary>
        ///  ICSharpCode.SharpZipLib.dll解压
        /// </summary>
        /// <param name="TargetFile"></param>
        /// <param name="fileDir"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string unZipFile(string TargetFile, string fileDir, ref string msg)
        {
            string rootFile = "";
            msg = "";
            try
            {
                //读取压缩文件（zip文件），准备解压缩
                ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
                ZipEntry entry;
                string path = fileDir;
                //解压出来的文件保存路径
                string rootDir = "";
                //根目录下的第一个子文件夹的名称
                while ((entry = inputstream.GetNextEntry()) != null)
                {
                    rootDir = Path.GetDirectoryName(entry.Name);
                    //得到根目录下的第一级子文件夹的名称
                    if (rootDir.IndexOf("\\") >= 0)
                    {
                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                    }
                    string dir = Path.GetDirectoryName(entry.Name);
                    //得到根目录下的第一级子文件夹下的子文件夹名称
                    string fileName = Path.GetFileName(entry.Name);
                    //根目录下的文件名称
                    if (dir != "")
                    {
                        //创建根目录下的子文件夹，不限制级别
                        if (!Directory.Exists(fileDir + "\\" + dir))
                        {
                            path = fileDir + "\\" + dir;
                            //在指定的路径创建文件夹
                            Directory.CreateDirectory(path);
                        }
                    }
                    else if (dir == "" && fileName != "")
                    {
                        //根目录下的文件
                        path = fileDir;
                        rootFile = fileName;
                    }
                    else if (dir != "" && fileName != "")
                    {
                        //根目录下的第一级子文件夹下的文件
                        if (dir.IndexOf("\\") > 0)
                        {
                            //指定文件保存路径
                            path = fileDir + "\\" + dir;
                        }
                    }
                    if (dir == rootDir)
                    {
                        //判断是不是需要保存在根目录下的文件
                        path = fileDir + "\\" + rootDir;
                    }

                    //以下为解压zip文件的基本步骤
                    //基本思路：遍历压缩文件里的所有文件，创建一个相同的文件
                    if (fileName != String.Empty)
                    {
                        FileStream fs = File.Create(path + "\\" + fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = inputstream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                               


                                fs.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        fs.Close();
                    }
                }
                inputstream.Close();
                msg = "解压成功！";
                return rootFile;
            }
            catch (Exception ex)
            {
                msg = "解压失败，原因：" + ex.Message;
                return "1;" + ex.Message;
            }
        }




        public Form4()
        {
            InitializeComponent();
        }
        XL.DownTaskInfo info = new XL.DownTaskInfo();
        private IntPtr a;





        /// <summary>
        /// 自创取文本中间
        /// </summary>
        /// <param name="startChar"></param>
        /// <param name="endChar"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        private string Match_Str(string startChar, string endChar, string str)
        {
            try
            {
                Regex reg = new Regex("(?<=" + startChar + ").*?(?=" + endChar + ")", RegexOptions.IgnoreCase);
                Match m = reg.Match(str);
                if (m.Success)
                {
                    return m.ToString();
                }
            }
            catch (System.Exception ex)
            {

            }
            return "";
        }



        private void button1_Click(object sender, EventArgs e)
        {

          //  var request = (HttpWebRequest)WebRequest.Create("https://cloud.189.cn/t/reMFBv32iMNz");
          //var response = (HttpWebResponse)request.GetResponse();         
       
          // var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();                                       
          //  string url= Match_Str("class=\"downloadUrl\" value=\"//", "\"", responseString);
          
          //  try
          //  {
          //      button1.Enabled = false;
          //      timer1.Enabled = true;
          //      timer1.Interval = 500;
          //      var initSuccess = XL.XL_Init();
          //      if (initSuccess)
          //      {
          //          XL.DownTaskParam p = new XL.DownTaskParam()
          //          {
          //              szTaskUrl = "http://" + url,
          //              szFilename = "1.MP3",
          //              szSavePath = AppDomain.CurrentDomain.BaseDirectory
          //          };
          //          a = XL.XL_CreateTask(p);
          //          var startSuccess = XL.XL_StartTask(a);
          //      }
          //      else
          //      {
          //          MessageBox.Show("XL_Init初始化失败");
          //      }
          //  }
          //  catch (Exception ex)
          //  {
          //      button1.Enabled = true;
          //      MessageBox.Show(ex.Message);
          //  }


        }
        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="fileToDecompress"></param>
        public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (DeflateStream decompressionStream = new DeflateStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                        MessageBox.Show("解压成功");
                    }
                }
            }
        }


        /// <summary>
        /// 解压多个文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        public class ZipHelper
        {
            #region 私有变量
            String the_rar;
            RegistryKey the_Reg;
            Object the_Obj;
            String the_Info;
            ProcessStartInfo the_StartInfo;
            Process the_Process;
            #endregion
            public void DeZip(string zipname, string zippath)
            {
                try
                {
                    the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
                    the_Obj = the_Reg.GetValue("");
                    the_rar = the_Obj.ToString();
                    the_Reg.Close();
                    the_rar = the_rar.Substring(1, the_rar.Length - 7);
                    the_Info = " X -y -ibck " + zipname + " " + zippath;
                    the_StartInfo = new ProcessStartInfo();
                    the_StartInfo.FileName = the_rar;
                    the_StartInfo.Arguments = the_Info;
                    the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    the_Process = new Process();
                    the_Process.StartInfo = the_StartInfo;
                    the_Process.Start();
                    the_Process.WaitForExit();


                }
                catch (Exception ex)
                {
                    MessageBox.Show("您没有装winrar压缩软件，请安装winrar软件");
                }
            }


        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            var qq = XL.XL_QueryTaskInfoEx(a, info);
            
            progressBar1.Value = (int)(info.fPercent * 100);          

           label1.Text = (info.nTotalSize/1000000 ).ToString()+" MB";
          
            label2.Text = (info.nSpeed/1000).ToString()+"KB";


            if (info.stat == XL.DOWN_TASK_STATUS.TSC_COMPLETE)
            {

                label3.Text = "解压中，请等侍";
                XL.XL_UnInit();            

                

               

                //unZipFile("game.zip", AppDomain.CurrentDomain.BaseDirectory,ref msg);
                ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                zip.ExtractZip("game.zip", AppDomain.CurrentDomain.BaseDirectory,"");
               
                // ZipHelper zipHelper = new ZipHelper();
                // zipHelper.DeZip("game.zip", AppDomain.CurrentDomain.BaseDirectory);
                label3.Text = "更新完成,可以关闭窗口";

                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.FileName = AppDomain.CurrentDomain.BaseDirectory + name1;//需要启动的程序名         //a启动参数 
                // p.StartInfo.Arguments = " -u " + responseString + " -p 1111 -z 1"; //启动参数  
               // p.StartInfo.Arguments = @url; //启动参数  
                                              //  MessageBox.Show(url);


                p.Start();//启动    

                //p.WaitForExit();




                //Process.GetCurrentProcess().Kill();
                System.Environment.Exit(0);

                //  MessageBox.Show("更新已完成");
            }
           

        }

        private void Form4_Load(object sender, EventArgs e)
        {

            //MessageBox.Show(AppDomain.CurrentDomain.BaseDirectory + name1);
            //return;

            //var request = (HttpWebRequest)WebRequest.Create("https://dj-1300382743.cos.ap-chengdu.myqcloud.com/url.txt");
            //var response = (HttpWebResponse)request.GetResponse();
            //var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            ////string url = Match_Str("class=\"downloadUrl\" value=\"//", "\"", responseString);

            //request = (HttpWebRequest)WebRequest.Create(responseString);
            //response = (HttpWebResponse)request.GetResponse();
            //responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();           
            


  

                          
            //string url = Match_Str("class=\"downloadUrl\" value=\"//", "\"", responseString);

           



            if (File.Exists("game.zip"))
            {
                File.Delete("game.zip");
            }
            if (File.Exists("game.zip.td"))
            {
                File.Delete("game.zip.td");
            }
            if (File.Exists("game.zip.td.cfg"))
            {
                File.Delete("game.zip.td.cfg");
            }


           // MessageBox.Show(url);
           // return;

            try
            {
                button1.Enabled = false;
                timer1.Enabled = true;
                timer1.Interval = 500;
                var initSuccess = XL.XL_Init();

                if (initSuccess)
                {
                    XL.DownTaskParam p = new XL.DownTaskParam()
                    {
                        szTaskUrl = "http://" + url,
                        szFilename = "game.zip",
                        szSavePath = AppDomain.CurrentDomain.BaseDirectory


                        
                    };
                    a = XL.XL_CreateTask(p);
                    var startSuccess = XL.XL_StartTask(a);
                }
                else
                {
                    MessageBox.Show("XL_Init初始化失败");
                }
            }
            catch (Exception ex)
            {
                button1.Enabled = true;
             //   MessageBox.Show(ex.Message);
            }

        }
    }
}
